package com.ynyr.jar.wss.handler;

import com.corundumstudio.socketio.AckRequest;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.annotation.OnConnect;
import com.corundumstudio.socketio.annotation.OnDisconnect;
import com.corundumstudio.socketio.annotation.OnEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;


@Slf4j
@Component
public class ChatMessageEventHandler
{  
    private final SocketIOServer server;

    @Autowired  
    public ChatMessageEventHandler(SocketIOServer server)
    {  
        this.server = server;  
    }  
    //添加connect事件，当客户端发起连接时调用，本文中将clientid与sessionid存入数据库  
    //方便后面发送消息时查找到对应的目标client,  
    @OnConnect
    public void onConnect(SocketIOClient client) {
        log.info("{} 客户端连接", client.getSessionId());
    }  
      
    //添加@OnDisconnect事件，客户端断开连接时调用，刷新客户端信息  
    @OnDisconnect
    public void onDisconnect(SocketIOClient client)  
    {
        log.info("{} 客户端连接断开", client.getSessionId());
    }  
      
    //广播消息
    @OnEvent(value = "chatevent")
    public void onEvent(SocketIOClient client, AckRequest request, String data) {
        log.info("server receive message is {}", data);
        server.getBroadcastOperations().sendEvent("chatevent", data);
    }
}  